<?php
/**
 * ClassName: treatemtn
 * Description:
 * @Author 周昌
 * @Create 2023/11/17 9:13
 */

namespace app;


use epii\admin\ui\lib\epiiadmin\jscmd\JsCmd;
use epii\server\Args;
use epii\ui\upload\AdminUiUpload;
use epii\ui\upload\driver\LocalFileUploader;
use model\TreatmentModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use service\admin\TreatmentCateService;
use service\admin\TreatmentService;
use service\admin\HospitalService;
use think\Db;

class treatment extends base
{
    public function init()
    {
        parent::init();
        $this->accessDenied();
    }
    public function index()
    {
        if($this->adminInfo['role']==1){
            $this->assign('hospitals',HospitalService::getSelect());
        }
        //筛选
        if($this->adminInfo['role']==1){
            $this->_as_treatmentCate = TreatmentCateService::getSelect();
        }else{
            $this->_as_treatmentCate = TreatmentCateService::getSelect(['hospital_id'=>$this->adminInfo['hospital_id']]);
        }
        $this->adminUiDisplay();
    }

    public function ajax_data()
    {
        $map = [];
        //登录用户权限判断
        $hospital_id=$this->adminInfo['hospital_id'];
        if($hospital_id){
            $map[]=['hospital_id','=',$hospital_id];
        }
        //分类
        $treatment_cate_id=Args::params('treatment_cate_id/d');;
        if($treatment_cate_id){
            $map[]=['treatment_cate_id','=',$treatment_cate_id];
        }

        $name = Args::params('name');
        if ($name) {
            $map[] = ['name', "LIKE", '%' . $name . '%'];
        }

        $hospital_id = Args::params('hospital_id');
        if ($hospital_id) {
            $map[] = ['hospital_id', "=", $hospital_id];
        }
        echo TreatmentService::getAjaxData($map);
    }

    public function add_edit()
    {
        $id = Args::params('id');
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = Args::params('r');
            //登录权限判断
            $hospital_id=$this->adminInfo['hospital_id'];
            if(!empty($hospital_id)){
                $data['hospital_id']=$hospital_id;
            }
            //验证
            $this->validate($data,[
                'name|治疗项目名称'=>'require',
                'hospital_id|所属医院'=>'require|integer|>=:0',
                'treatment_cate_id|分类'=>'require|integer|>=:0',
                'performance|绩效'=>'require|float|>=:0',
                'status|状态'=>'require|integer|>=:0',
                'sort|排序'=>'integer|>=:0',
            ]);
            if ($id) {
                $res = TreatmentService::edit($id,$data);
            } else {
                $data['addtime']=time();
                $res = TreatmentService::add($data);
            }
            $res['code']?$this->success($res['msg']):$this->error($res['msg']);
        }
        $this->_as_info = $id ? TreatmentModel::getInfo(['id'=>$id]) : [];
        $this->_as_id = $id;
        $this->_as_status = TreatmentService::statusSelect();
        if($this->adminInfo['role']==1){
            $this->_as_hospitals = HospitalService::getSelect();
            $this->_as_treatmentCate = TreatmentCateService::getSelect();
        }else{
            $this->_as_treatmentCate = TreatmentCateService::getSelect(['hospital_id'=>$this->adminInfo['hospital_id']]);
        }

        $this->adminUiDisplay();
    }
    //修改状态
    public function status(){
        $id=Args::params('id/d/1','id,不能为空');
        $status=Args::params('status');
        $res=TreatmentService::status($id,$status);
        if($res['code']){
            $this->success('成功','refresh');
        }
        $this->error();
    }

    /**
     * @return array|false|string* 删除
     */
    public function del()
    {
        $id = Args::params('id');
        //todo 判断治疗项目下是否已经有订单，无则可以删除
        $res = TreatmentService::del($id);
        if ($res['code']) {
            $this->success($res['msg'],'refresh');
        } else {
            $this->error($res['msg']);
        }
    }
    // 问诊 通过 分类id 获取 治疗项目列表
    public function getTreatmentList()
    {
        $treatment_cate_id=Args::params('treatment_cate_id/d');
        $list=TreatmentModel::getList(['treatment_cate_id'=>$treatment_cate_id],'id,name,price');
        exit(json_encode($list));
    }
    //导入
    public function import(){

        //获取上次的文件
//        $upload_file = $_FILES['path']['tmp_name'];
        $path = Args::params('path');
        $upload_file = LocalFileUploader::getInitUploadUrlPre().str_replace('\\','/',$path);
//        var_dump($upload_file);
//        var_dump($_FILES);
//        var_dump($path);
//        die;
        //自动获取文件类型 (xlsx,xls,csv)
        $spreadsheet = IOFactory::load($upload_file);
        $worksheet = $spreadsheet->getActiveSheet();
        // 总行数
        $highestRow = $worksheet->getHighestRow();
        // 总列数
        $highestColumn = $worksheet->getHighestColumn();

        $lines = $highestRow - 1;
        if ($lines <= 0) {
            return JsCmd::alert("暂无数据");
        }
        $arr = [];
        //第二行开始
        for ($row = 2; $row <= $highestRow; ++$row) {
            //根据自身逻辑获取需求的数据进行解析
            $name = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //昵称
            $realname = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //姓名
            $phone = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //手机号
            $status = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //状态
//            $addtime = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //创建时间
            $updatetime = $worksheet->getCellByColumnAndRow(6, $row)->getValue(); //更新时间
            if($name){
                $arr[] = [
                    'name'=>$name,
                    'realname'=>$realname,
                    'phone'=>$phone,
                    'status'=>$status,
                    'updatetime'=>$updatetime?strtotime($updatetime):null,

                ];
            }
        }
//        print_r($arr);
//        die;
        $res=Db::name('user')->limit(10)->insertAll($arr,true);
        if ($res) {
            return JsCmd::alertCloseRefresh("成功");
        } else {
            return JsCmd::alert("操作失败");
        }

    }
    public function img()
    {
        echo AdminUiUpload::doUpload(["gif", "jpeg", "jpg", "png","xls","xlsx"], 2048000);
        exit;
    }


}